﻿using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using Febucci.UI;
using Gp.Scripts.Core;
using QFramework;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Gp.Scripts.GUI {
    public class TurnChangeWindow : MonoBehaviour, IController {
        public Transform lineParent;
        private List<Image> _images;
        
        [SerializeField] private TextAnimatorPlayer playerTextAnimator;
        [SerializeField] private TextAnimatorPlayer turnTextAnimator;
        
        
        
        private void Start() {
            _images = new List<Image>();
            for (int i = 0; i < lineParent.childCount; i++) {
                var img = lineParent.GetChild(i).GetComponent<Image>();
                if (img != null)
                    _images.Add(img);
            }


            this.RegisterEvent<TurnResolveEvent>(OnTurnChange).UnRegisterWhenGameObjectDestroyed(gameObject);
        }

        private void OnTurnChange(TurnResolveEvent obj) {
            StartCoroutine(SwitchEffect(obj));
        }


        private IEnumerator SwitchEffect(TurnResolveEvent obj) {
            Global.Get<BattleSystem>().BlockInput(this);
            
            var playerText = obj.CurrentPlayer.PlayerNumber switch {
                PlayerConst.PlayerUnitNumber => "你的回合",
                PlayerConst.AIUnitNumber => "对方回合",
                _ => ""
            };

            var turnText = obj.TurnState switch {
                TurnState.RoundEnding => "",
                TurnState.Attack => "进攻轮",
                TurnState.Defense => "防守轮",
                _ => throw new ArgumentOutOfRangeException()
            };


            
            playerTextAnimator.ShowText(playerText);
            turnTextAnimator.ShowText(turnText);
            
            
            foreach (var img in _images) {
                if (obj.CurrentPlayer.PlayerNumber == PlayerConst.PlayerUnitNumber) {
                    img.fillAmount = 1;
                    img.DOFillAmount(0.1f, 1.25f);
                }
                else {
                    img.fillAmount = 0;
                    img.DOFillAmount(1f, .75f);
                }
            }
            yield return new WaitForSeconds(2f);
            
            Global.Get<BattleSystem>().UnBlockInput(this);
        }


        public IArchitecture GetArchitecture() {
            return MainArchitecture.Interface;
        }
    }
}